<template>
  <div>
    <div class="player">
      <audio :src="url" ref="music" @ended="ended"></audio>
    </div>

    <div class="main" onselectstart="return false;">
      <Left
        :currentPlayInfoIsShow="currentPlayInfoIsShow"
        :picUrl="picUrl"
        :musicName="musicName"
        :isPlaying="isPlaying"
        @play="play"
        @pause="pause"
        @preAndNext="preAndNext"
      ></Left>

      <div class="right">
        <div class="play-control">
          <div class="time-progress yahei">{{ playTime }}</div>
          <div class="main-progress">
            <div
              class="progress-bar hover-hand"
              ref="progressBar"
              @click="playProgressClick"
            >
              <div class="control" ref="currentProgressBar">
                <!-- <div
                  class="circle"
                ></div> -->
              </div>
            </div>
          </div>
          <div class="time-progress yahei">{{ allTime }}</div>
        </div>

        <div class="vol-control">
          <div @click="voiceClick">
            <i class="iconfont yahei hover-hand" v-show="voice">&#xe60b;</i>
            <i class="iconfont yahei hover-hand" v-show="!voice">&#xe609;</i>
          </div>
          <div class="vol-progress">
            <div class="main-progress hover-hand">
              <div
                class="progress-bar"
                @click="volProgressClick"
                ref="volProgressBar"
              >
                <div class="control" ref="volCurrentProgressBar">
                  <!-- <div
                    class="circle"
                  ></div> -->
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="other-control">
          <div @click="togglePlayModel">
            <i
              class="iconfont yahei hover-hand"
              v-show="toggleShowPlayModel === 0"
              >&#xe6a1;</i
            >
            <i
              class="iconfont yahei hover-hand"
              v-show="toggleShowPlayModel === 1"
              >&#xe6a0;
            </i>
            <i
              class="iconfont yahei hover-hand"
              v-show="toggleShowPlayModel === 2"
              >&#xe6a2;</i
            >
          </div>
          <i
            class="iconfont yahei hover-hand"
            @click="showLyric"
            :style="showLyricIsShow ? 'color:lightseagreen' : ''"
            >&#xe727;</i
          >
          <i
            class="iconfont yahei hover-hand"
            :class="PlayMusicListIsShow ? 'active' : ''"
            @click="showPlayMusicList"
            >&#xe699;</i
          >

          <!-- <transition name="el-zoom-in-bottom"> -->
          <!-- <transition name="fade">
            <div class="play-music-list" v-show="PlayMusicListIsShow">
              <PlayMusicList
                :playingSongsList="playingSongsList"
              ></PlayMusicList>
            </div>
          </transition> -->
          <!-- </transition> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from "dayjs";

import { getMusicUrl } from "network/player.js";
import { getSongDetail } from "network/recommend.js";
import bus from "utils/bus.js";

import Left from "./childComponents/left.vue";
// import PlayMusicList from "./childComponents/playMusicList.vue";
//这里引入播放歌单的回暖无法解决显示层级问题
export default {
  name: "Player",
  data() {
    return {
      url: "",
      id: "",
      isPlaying: true,
      playProgressBarLength: 0,
      //拖拽事件就不做了，逻辑都差不多
      // playProgressCircleMouseIsDown: false,
      volProgressBarLength: 0,
      // volProgressCircleMouseIsDown: false,
      toggleShowPlayModel: 0,
      showLyricIsShow: false,
      voice: true,
      curTime: 0,
      ctime: {},
      totalTime: 0,
      picUrl: "",
      musicName: "",
      currentPlayInfoIsShow: false,
      // playProgressClickTime:0,
      volume: 0,
      PlayMusicListIsShow: false,
      playingSongsList: [],
      playingSongIndex: -1,
    };
  },

  components: {
    Left,
  },

  computed: {
    playBar() {
      return this.$refs.progressBar.clientWidth;
    },
    volBar() {
      return this.$refs.volProgressBar.clientWidth;
    },
    playTime() {
      return dayjs(this.curTime).format("mm:ss");
    },
    allTime() {
      return dayjs(this.totalTime).format("mm:ss");
    },
  },

  methods: {
    play() {
      this.$refs.music.play();
      this.ctime = setInterval(() => {
        this.curTime = this.$refs.music.currentTime * 1000;
      }, 500);
      this.isPlaying = false;
      bus.$emit("pauseAndPlay");
    },
    pause() {
      this.$refs.music.pause();
      this.isPlaying = true;

      //关闭获取当前时间的定时器
      clearInterval(this.ctime);
      bus.$emit("pauseAndPlay");
    },
    preAndNext(t) {
      if (this.playingSongsList.length > 0) {
        if (this.playingSongIndex + t < 0) {
          alert("没有上一曲了...");
          return;
        } else if (
          this.playingSongIndex + t >
          this.playingSongsList.length - 1
        ) {
          alert("没有下一曲了...");
          return;
        } else {
          this.playingSongIndex += t;
          getMusicUrl(this.playingSongsList[this.playingSongIndex].id).then(
            (res) => {
              this.url = res.data.data[0].url;
            }
          );
          // this.totalTime = this.playingSongsList[this.playingSongIndex].dt;
          bus.$emit("ended", this.playingSongIndex);
          //更新id
          this.id = this.playingSongsList[this.playingSongIndex].id;

          getSongDetail(this.id).then((res) => {
            // console.log(res.data.songs[0]);
            this.totalTime = res.data.songs[0].dt;
            this.picUrl = res.data.songs[0].al.picUrl;
            this.musicName = res.data.songs[0].name;
          });
        }
      }
    },
    ended() {
      // console.log(this.toggleShowPlayModel, "播放结束", this.loop);
      this.isPlaying = true;
      if (this.toggleShowPlayModel === 0) {
        //顺序播放
        if (this.playingSongIndex < this.playingSongsList.length - 1) {
          this.playingSongIndex++;
          this.id = this.playingSongsList[this.playingSongIndex].id;
          getMusicUrl(this.id).then((res) => {
            this.url = res.data.data[0].url;
          });
          // this.totalTime = this.playingSongsList[this.playingSongIndex].dt;
          bus.$emit("ended", this.playingSongIndex);
          getSongDetail(this.playingSongsList[this.playingSongIndex].id).then(
            (res) => {
              // console.log(res.data.songs[0]);
              this.totalTime = res.data.songs[0].dt;
              this.picUrl = res.data.songs[0].al.picUrl;
              this.musicName = res.data.songs[0].name;
              // setTimeout(() => {
              //   this.currentPlayInfoIsShow = true;
              // }, 1000);
            }
          );
        }
      } else if (this.toggleShowPlayModel === 1) {
        //随机播放
        // console.log(this.playingSongIndex);
        let length = this.playingSongsList.length;
        let redomN;
        for (let i = 0; i < 1; i++) {
          redomN = Math.floor(Math.random() * length);
          if (redomN === this.playingSongIndex) {
            i--;
          } else {
            this.playingSongIndex = redomN;
            // console.log(redomN);
            this.id = this.playingSongsList[this.playingSongIndex].id;

            getMusicUrl(this.id).then((res) => {
              this.url = res.data.data[0].url;
            });
            // this.totalTime = this.playingSongsList[this.playingSongIndex].dt;
            bus.$emit("ended", this.playingSongIndex);
            getSongDetail(this.id).then((res) => {
              // console.log(res.data.songs[0]);
              this.totalTime = res.data.songs[0].dt;
              this.picUrl = res.data.songs[0].al.picUrl;
              this.musicName = res.data.songs[0].name;
              // setTimeout(() => {
              //   this.currentPlayInfoIsShow = true;
              // }, 1000);
            });
          }
        }
      } else if (this.toggleShowPlayModel === 2) {
        //单曲循环
        this.playingSongIndex = this.playingSongIndex;
        this.$refs.music.play();
        this.isPlaying = false;
      }
    },

    //播放进度条的点击事件
    playProgressClick(e) {
      // console.log(e.clientX - this.$refs.progressBar.offsetLeft);
      this.playProgressBarLength =
        e.clientX - this.$refs.progressBar.offsetLeft;
      // this.$refs.currentProgressBar.style.width = this.playProgressBarLength + "px";
      let playProgressClickTime =
        (this.playProgressBarLength / this.$refs.progressBar.clientWidth) *
        this.totalTime;
      this.$refs.music.currentTime = playProgressClickTime / 1000;

      //通知详情页
      bus.$emit("playProgressBarClick", this.$refs.music.currentTime * 1000);
    },

    //音量按钮点击事件
    voiceClick() {
      this.voice = !this.voice;
      if (!this.voice) {
        this.$refs.volCurrentProgressBar.style.width = 0;
        this.$refs.music.volume = 0;
      } else {
        this.$refs.volCurrentProgressBar.style.width = "100%";
        this.$refs.music.volume = 1;
      }
    },

    //音量控制条的点击事件
    volProgressClick(e) {
      this.volProgressBarLength =
        e.clientX - this.$refs.volProgressBar.offsetLeft;
      this.$refs.music.volume =
        this.volProgressBarLength / this.$refs.volProgressBar.clientWidth;
      this.$refs.volCurrentProgressBar.style.width =
        this.$refs.music.volume * 100 + "%";
      // console.log(this.$refs.volCurrentProgressBar.style.width < '10px');
      if (this.volProgressBarLength < 3) {
        this.voice = false;
      } else {
        this.voice = true;
      }
    },

    //播放模式切换
    togglePlayModel() {
      this.toggleShowPlayModel++;
      if (this.toggleShowPlayModel === 3) {
        this.toggleShowPlayModel = 0;
      }
    },

    //桌面歌词展示
    showLyric() {
      this.showLyricIsShow = !this.showLyricIsShow;
      // this.showLyricIsShow = !this.showLyricIsShow;
      bus.$emit("toggleDesklrc", this.showLyricIsShow);
    },

    //正在播放歌单展示
    showPlayMusicList() {
      this.PlayMusicListIsShow = !this.PlayMusicListIsShow;
      bus.$emit("showPlaymusicList", this.PlayMusicListIsShow);
    },
  },

  created() {
    bus.$on("play", (id, newSongList, index) => {
      this.id = id;
      //获取发射play事件歌曲在歌单中的index
      this.playingSongIndex = index;
      // console.log(id);
      //获取播放url
      getMusicUrl(id).then((res) => {
        this.url = res.data.data[0].url;
      });
      this.isPlaying = false;
      //获取歌曲详细信息
      getSongDetail(id).then((res) => {
        // console.log(res.data.songs[0]);
        this.totalTime = res.data.songs[0].dt;
        this.picUrl = res.data.songs[0].al.picUrl;
        this.musicName = res.data.songs[0].name;
        setTimeout(() => {
          this.currentPlayInfoIsShow = true;
        }, 1000);
      });

      //播放队列相关
      //获取ids
      // console.log(newSongList);
      //拿到歌单里所有歌曲的id
      let ids = [];
      newSongList.forEach((element) => {
        ids.push(element.id);
      });
      ids = ids.join();
      //拿着id发送请求获取歌曲信息
      getSongDetail(ids).then((res) => {
        this.playingSongsList = res.data.songs;
      });
    });

    bus.$on("pMusicListplay", (ind) => {
      this.playingSongIndex = ind;

      this.id = this.playingSongsList[ind].id;

      getMusicUrl(this.id).then((res) => {
        this.url = res.data.data[0].url;
      });

      getSongDetail(this.playingSongsList[ind].id).then((res) => {
        // console.log(res.data.songs[0]);
        this.totalTime = res.data.songs[0].dt;
        this.picUrl = res.data.songs[0].al.picUrl;
        this.musicName = res.data.songs[0].name;
      });
    });

    bus.$on("musicListPlayAll", (songs) => {
      this.playingSongsList = songs;
      this.playingSongIndex = 0;
      this.id = this.playingSongsList[0].id;
      setTimeout(() => {
        this.currentPlayInfoIsShow = true;
      }, 1000);
      bus.$emit("musicPlaying", this.playingSongIndex);
      getMusicUrl(this.playingSongsList[0].id).then((res) => {
        this.url = res.data.data[0].url;
      });

      getSongDetail(this.id).then((res) => {
        // console.log(res.data.songs[0]);
        this.totalTime = res.data.songs[0].dt;
        this.picUrl = res.data.songs[0].al.picUrl;
        this.musicName = res.data.songs[0].name;
      });
    });
  },

  watch: {
    url(a) {
      if (a) {
        bus.$emit("isPlaying", this.id);
        //获取到新的url就开始自动播放
        setTimeout(() => {
          document.querySelector("audio").play();
        }, 100);

        //播放控件显示暂停
        this.isPlaying = false;
        this.volume = this.$refs.music.volume;

        //开启定时器，获取当前播放时间
        this.ctime = setInterval(() => {
          this.curTime = this.$refs.music.currentTime * 1000;
        }, 500);
      }
    },

    curTime(newT) {
      // console.log(newT/this.totalTime*100 + '%');
      this.$refs.currentProgressBar.style.width =
        (newT / this.totalTime) * 100 + "%";

      bus.$emit("timeMove", newT);
    },

    playingSongsList(newList) {
      bus.$emit("playListUpdate", newList);
    },
  },
};
</script>

<style lang="less" scoped>
// .player {
//   position: fixed;
//   right: 30px;
//   bottom: 90px;
//   z-index: 100;
//   .audiotest {
//     background-color: silver;
//   }
// }
.main {
  position: fixed;
  display: flex;
  z-index: 999;
  bottom: 0;
  background-color: #f1f1f1;
  width: 100%;
  height: 0.541667rem;

  .right {
    display: flex;
    flex: 1;
    display: flex;
    .play-control {
      display: flex;
      justify-content: space-between;
      margin: 0 0.125rem;
      height: 100%;
      width: 888px;
      .time-progress {
        font-size: 0.125rem;
        line-height: 0.541667rem;
        padding: 0 0.083333rem;
      }
    }
    .vol-control {
      height: 100%;
      width: 1.333333rem;
      display: flex;
      align-items: center;
      .vol-progress {
        flex: 1;
        display: flex;
        margin: 0 0.05rem;
        height: 100%;
        align-items: center;
      }
    }
    .other-control {
      position: relative;
      margin: 0 0.166667rem;
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
      // .play-music-list {
      //   position: absolute;
      //   z-index: 1001;
      //   top: -4.166666rem;
      //   right: -0.166666rem;
      //   border-radius: 0.083333rem;
      //   width: 4.166666rem;
      //   height: 4.166666rem;
      //   overflow: hidden;
      //   background-color: #ffffff;
      // }
    }
  }
}

.main-progress {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  flex: 1;
  .progress-bar {
    position: relative;
    width: 95%;
    border-radius: 5px;
    height: 4px;
    background-color: #ddccc9;
    .control {
      position: absolute;
      left: 0;
      width: 1px;
      border-radius: 5px;
      height: 4px;
      background-color: #42dbdf;
      .circle {
        position: absolute;
        top: -0.025rem;
        right: -0.025rem;
        width: 0.1rem;
        height: 0.1rem;
        border-radius: 50%;
        background-color: lightseagreen;
      }
    }
  }
}

.vol-control .vol-progress .control {
  width: 100%;
}

.active {
  color: lightseagreen;
}

// @keyframes show-music-list {
//   0% {
//     right: -4.166667rem;
//   }
//   100% {
//     right: -0.166666rem;
//   }
// }
// // .show-list {
// //   animation: show-music-list 0.5s ease;
// // }
// // .hidden-list {
// //   animation: show-music-list 0.5s ease;
// //   animation-direction: reverse;
// // }
// .fade-enter-active {
//   animation: show-music-list 0.5s ease;
// }
// .fade-leave-active {
//   animation: show-music-list 0.5s ease reverse;
// }
</style>
